package com.xindong.paking.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xindong.paking.entity.LoginAdminResponseResult;
import com.xindong.paking.entity.TbRole;
import com.xindong.paking.mapper.TbRoleMapper;
import com.xindong.paking.service.LoginAdminService;
import com.xindong.paking.utils.JwtUtil;
import com.xindong.paking.utils.Result;
import com.xindong.paking.utils.ResultStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class LoginAdminServiceImpl implements LoginAdminService {
    @Autowired
    private TbRoleMapper tbRoleMapper;

    @Override
    public Result login(String username, String password) {

        // 查询账号
        QueryWrapper<TbRole> tbUserQueryWrapper = new QueryWrapper<>();
        tbUserQueryWrapper.eq("account", username);
        TbRole tbRole = tbRoleMapper.selectOne(tbUserQueryWrapper);
        // 如果账号为空
        if (tbRole == null) {
            return new Result(ResultStatus.USER_PASSWORD_ERROR);
        }


        // 验证密码
//        boolean check = BCrypt.checkpw(password, tbRole.getPassword());
        boolean check = password.equals(tbRole.getPassword());
        if (!check) {
            return new Result(ResultStatus.USER_PASSWORD_ERROR);
        }


        // 设置密码为空，返回前端用户信息
        tbRole.setPassword(null);

        // 将数据转入map当中
        Map<String, Object> userMap = new HashMap<String, Object>();
        userMap = JSON.parseObject(JSON.toJSONString(tbRole), new TypeReference<Map<String, Object>>() {});

        // 获取token
        String token = JwtUtil.sign(tbRole.getId().toString(), userMap);

        // 返回参数
        LoginAdminResponseResult loginResponseResult = new LoginAdminResponseResult(token, tbRole);

        return new Result(200, "登陆成功", loginResponseResult);
    }
}
